package com.petcommunity.servlet;

import com.petcommunity.dao.UserDAO;
import com.petcommunity.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.regex.Pattern;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    // 密码正则表达式：6-20位，必须同时包含大小写字母和数字
    private static final String PASSWORD_PATTERN =
            "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[A-Za-z\\d]{6,20}$";

    private static final Pattern pattern = Pattern.compile(PASSWORD_PATTERN);

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置请求编码为 UTF-8
        request.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");

        HttpSession session = request.getSession();

        try {
            // 1. 验证参数是否为空
            if (username == null || username.trim().isEmpty()) {
                session.setAttribute("error", "用户名不能为空");
                response.sendRedirect("register.jsp");
                return;
            }

            if (password == null || password.trim().isEmpty()) {
                session.setAttribute("error", "密码不能为空");
                response.sendRedirect("register.jsp");
                return;
            }

            if (confirmPassword == null || confirmPassword.trim().isEmpty()) {
                session.setAttribute("error", "确认密码不能为空");
                response.sendRedirect("register.jsp");
                return;
            }

            // 2. 验证两次密码是否一致
            if (!password.equals(confirmPassword)) {
                session.setAttribute("error", "两次输入的密码不一致");
                response.sendRedirect("register.jsp");
                return;
            }

            // 3. 验证密码格式
            if (!isValidPassword(password)) {
                session.setAttribute("error", "密码格式不正确：需6-20位，必须同时包含大小写字母和数字");
                response.sendRedirect("register.jsp");
                return;
            }

            // 4. 验证用户名长度
            if (username.length() > 20) {
                session.setAttribute("error", "用户名长度不能超过20个字符");
                response.sendRedirect("register.jsp");
                return;
            }

            // 5. 检查用户名是否已存在
            UserDAO userDAO = new UserDAO();
            User existingUser = userDAO.getUserByUsername(username);
            if (existingUser != null) {
                session.setAttribute("error", "用户名已存在，请选择其他用户名");
                response.sendRedirect("register.jsp");
                return;
            }

            // 6. 创建新用户
            User newUser = new User();
            newUser.setUsername(username.trim());
            newUser.setPassword(password);
            newUser.setRole("user");  // 普通用户默认角色

            userDAO.addUser(newUser);

            // 注册成功，设置成功消息并跳转到登录页面
            session.setAttribute("success", "注册成功！请登录");
            response.sendRedirect("login.jsp");

        } catch (Exception e) {
            // 处理异常
            session.setAttribute("error", "注册失败，请稍后重试");
            response.sendRedirect("register.jsp");
            e.printStackTrace(); // 在实际项目中建议使用日志框架记录异常
        }
    }

    /**
     * 验证密码格式
     * @param password 密码
     * @return 是否符合要求
     */
    private boolean isValidPassword(String password) {
        return pattern.matcher(password).matches();
    }
}